<template>
  <div class="home">
    <div class="header">
      <h1>茯神</h1>
      <div class="header-buttons">
        <button @click="showTopicModal = true" class="create-button topic-button">
          🏷️ 管理主题
        </button>
        
      </div>
    </div>
    
    <!-- 保存提示 -->
    <div v-if="saveMessage" class="save-message" :class="saveMessageType">
      {{ saveMessage }}
    </div>
    
    <!-- 主题选择区域 -->
    <div class="topics-section" v-if="topics.length > 0">
      <h3>选择主题工作空间</h3>
      <div class="topics-grid">
        <div 
          v-for="topic in topics" 
          :key="topic.id" 
          class="topic-card"
          :class="{ active: selectedTopicId === topic.id }"
          @click="selectTopic(topic.id)"
          :style="{ borderColor: topic.color }"
        >
          <div class="topic-icon" :style="{ backgroundColor: topic.color }">
            {{ topic.icon || '📝' }}
          </div>
          <div class="topic-info">
            <h4>{{ topic.title }}</h4>
            <p>{{ topic.description }}</p>
            <small class="topic-hint">点击进入工作空间</small>
          </div>
        </div>
      </div>
    </div>
    
    <div class="documents-section">
      <h2>我的文档</h2>
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="!documentTree || documentTree.length === 0" class="empty-state">
        <p>还没有文档，点击上面的按钮创建一个新文档或文件夹吧！</p>
      </div>
      <div v-else class="documents-tree">
        <DocumentTreeItem 
          v-for="item in documentTree" 
          :key="item.id" 
          :item="item"
          :depth="0"
          @open="openDocument"
          @move="handleMove"
          @delete="deleteDocument"
          @create-document="createNewDocument"
          @create-folder="createNewFolder"
        />
      </div>
    </div>
    
    <!-- 主题管理弹窗 -->
    <div v-if="showTopicModal" class="modal-overlay" @click="closeTopicModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>主题管理</h3>
          <button @click="closeTopicModal" class="close-btn">×</button>
        </div>
        
        <div class="modal-body">
          <!-- 创建新主题 -->
          <div class="create-topic-form">
            <h4>创建新主题</h4>
            <div class="form-group">
              <label>主题名称：</label>
              <input v-model="newTopic.title" type="text" placeholder="请输入主题名称" />
            </div>
            <div class="form-group">
              <label>描述：</label>
              <input v-model="newTopic.description" type="text" placeholder="请输入主题描述" />
            </div>
            <div class="form-group">
              <label>图标：</label>
              <div class="icon-selector">
                <span 
                  v-for="icon in iconOptions" 
                  :key="icon" 
                  class="icon-option"
                  :class="{ selected: newTopic.icon === icon }"
                  @click="newTopic.icon = icon"
                >
                  {{ icon }}
                </span>
              </div>
            </div>
            <div class="form-group">
              <label>颜色：</label>
              <div class="color-selector">
                <span 
                  v-for="color in colorOptions" 
                  :key="color" 
                  class="color-option"
                  :class="{ selected: newTopic.color === color }"
                  :style="{ backgroundColor: color }"
                  @click="newTopic.color = color"
                ></span>
              </div>
            </div>
            <button @click="createTopic" class="btn-primary" :disabled="!newTopic.title">
              创建主题
            </button>
          </div>
          
          <!-- 现有主题列表 -->
          <div class="existing-topics">
            <h4>现有主题</h4>
            <div class="topic-list">
              <div 
                v-for="topic in topics" 
                :key="topic.id" 
                class="topic-item"
              >
                <div class="topic-preview">
                  <span class="topic-icon" :style="{ backgroundColor: topic.color }">
                    {{ topic.icon || '📝' }}
                  </span>
                  <div class="topic-details">
                    <h5>{{ topic.title }}</h5>
                    <p>{{ topic.description }}</p>
                  </div>
                </div>
                <div class="topic-actions">
                  <button 
                    v-if="!topic.is_default" 
                    @click="setDefaultTopic(topic.id)" 
                    class="btn-secondary"
                  >
                    设为默认
                  </button>
                  <button 
                    v-if="!topic.is_default" 
                    @click="deleteTopic(topic.id)" 
                    class="btn-danger"
                  >
                    删除
                  </button>
                  <span v-if="topic.is_default" class="default-badge">默认</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import DocumentTreeItem from '../components/DocumentTreeItem.vue'

interface Document {
  id: number
  title: string
  content?: string
  type: 'document' | 'folder'
  parent_id?: number
  topic_id?: number
  sort_order: number
  created_at: string
  updated_at: string
  children?: Document[]
}

interface Topic {
  id: number
  title: string
  description?: string
  color: string
  icon?: string
  created_by?: number
  is_default: boolean
  sort_order: number
  created_at: string
  updated_at: string
}

const router = useRouter()
const documents = ref<Document[]>([])
const documentTree = ref<Document[]>([])
const topics = ref<Topic[]>([])
const selectedTopicId = ref<number | null>(null)
const loading = ref(true)
const currentUser = ref<any>(null)
// 添加保存提示信息
const saveMessage = ref('')
const saveMessageType = ref<'success' | 'error'>('success')

// 主题管理相关
const showTopicModal = ref(false)
const newTopic = ref({
  title: '',
  description: '',
  color: '#42b983',
  icon: '📝'
})

// 图标选项
const iconOptions = ['📝', '💼', '📚', '📈', '🛠️', '🎨', '🔬', '🎯', '💡', '❤️']

// 颜色选项
const colorOptions = ['#42b983', '#2196f3', '#ff9800', '#9c27b0', '#607d8b', '#f44336', '#4caf50', '#ff5722', '#795548', '#009688']

// 创建新文档
const createNewDocument = async (parentId?: number) => {
  if (!currentUser.value) return
  
  try {
    const response = await fetch('http://localhost:3000/api/documents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: '新文档 ' + new Date().toLocaleString(),
        content: '',
        type: 'document',
        parent_id: parentId,
        owner_id: currentUser.value.id,
        topic_id: selectedTopicId.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      saveMessage.value = '文档创建成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      // 跳转到编辑页面
      router.push(`/editor?id=${data.document.id}`)
    } else {
      console.error('Failed to create document:', data.error)
      saveMessage.value = '文档创建失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Create document error:', err)
    saveMessage.value = '文档创建失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 创建新文件夹
const createNewFolder = async (parentId?: number) => {
  if (!currentUser.value) return
  
  const folderName = prompt('请输入文件夹名称:', '新文件夹')
  if (!folderName) return
  
  try {
    const response = await fetch('http://localhost:3000/api/documents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: folderName,
        type: 'folder',
        parent_id: parentId,
        owner_id: currentUser.value.id,
        topic_id: selectedTopicId.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      saveMessage.value = '文件夹创建成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      // 重新加载文档列表
      loadDocuments()
    } else {
      console.error('Failed to create folder:', data.error)
      saveMessage.value = '文件夹创建失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Create folder error:', err)
    saveMessage.value = '文件夹创建失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 打开文档
const openDocument = (item: Document) => {
  if (item.type === 'document') {
    router.push(`/editor?id=${item.id}`)
  }
}

// 移动文档
const handleMove = (event: { itemId: number, newParentId?: number }) => {
  moveDocument(event.itemId, event.newParentId)
}

const moveDocument = async (itemId: number, newParentId?: number) => {
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${itemId}/move`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        parent_id: newParentId
      })
    })
    
    if (response.ok) {
      saveMessage.value = '移动成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      loadDocuments()
    } else {
      const data = await response.json()
      saveMessage.value = '移动失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Move document error:', err)
    saveMessage.value = '移动失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 删除文档/文件夹
const deleteDocument = async (item: Document) => {
  const confirmMessage = item.type === 'folder' 
    ? `确定要删除文件夹 "${item.title}" 及其所有内容吗？`
    : `确定要删除文档 "${item.title}" 吗？`
  
  if (!confirm(confirmMessage)) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${item.id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      saveMessage.value = `${item.type === 'folder' ? '文件夹' : '文档'}删除成功！`
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      loadDocuments()
    } else {
      const data = await response.json()
      saveMessage.value = `删除失败：${data.error || '未知错误'}`
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Delete document error:', err)
    saveMessage.value = '删除失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载文档列表
const loadDocuments = async () => {
  if (!currentUser.value) {
    loading.value = false;
    return;
  }
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/user/${currentUser.value.id}/tree`)
    const data = await response.json()
    
    if (response.ok) {
      if (data && Array.isArray(data.tree)) {
        documentTree.value = data.tree
      } else {
        documentTree.value = []
      }
    } else {
      console.error('Failed to load documents:', data.error)
      documentTree.value = []
    }
  } catch (err) {
    console.error('Load documents error:', err)
    documentTree.value = []
  } finally {
    loading.value = false
  }
}

// 获取当前用户
const getCurrentUser = () => {
  const user = localStorage.getItem('user')
  if (user) {
    try {
      currentUser.value = JSON.parse(user)
    } catch (e) {
      console.error('Failed to parse user from localStorage:', e)
      currentUser.value = null
    }
  }
}

onMounted(() => {
  getCurrentUser()
  loadTopics()
  loadDocuments()
})

// ======================== 主题管理方法 ========================

// 加载主题列表
const loadTopics = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/topics')
    const data = await response.json()
    
    if (response.ok) {
      topics.value = data.topics || []
      // 设置默认选中的主题
      const defaultTopic = topics.value.find(t => t.is_default)
      if (defaultTopic) {
        selectedTopicId.value = defaultTopic.id
      }
    } else {
      console.error('Failed to load topics:', data.error)
    }
  } catch (err) {
    console.error('Load topics error:', err)
  }
}

// 选择主题
const selectTopic = (topicId: number) => {
  // 跳转到主题工作空间
  router.push(`/topic/${topicId}`)
}

// 创建主题
const createTopic = async () => {
  if (!newTopic.value.title || !currentUser.value) return
  
  try {
    const response = await fetch('http://localhost:3000/api/topics', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: newTopic.value.title,
        description: newTopic.value.description,
        color: newTopic.value.color,
        icon: newTopic.value.icon,
        createdBy: currentUser.value.id
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      saveMessage.value = '主题创建成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      // 重置表单
      newTopic.value = {
        title: '',
        description: '',
        color: '#42b983',
        icon: '📝'
      }
      
      // 重新加载主题列表
      loadTopics()
    } else {
      console.error('Failed to create topic:', data.error)
      saveMessage.value = '主题创建失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Create topic error:', err)
    saveMessage.value = '主题创建失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 设置默认主题
const setDefaultTopic = async (topicId: number) => {
  try {
    const response = await fetch(`http://localhost:3000/api/topics/${topicId}/default`, {
      method: 'PUT'
    })
    
    if (response.ok) {
      saveMessage.value = '默认主题设置成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      loadTopics()
    } else {
      const data = await response.json()
      saveMessage.value = '设置失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Set default topic error:', err)
    saveMessage.value = '设置失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 删除主题
const deleteTopic = async (topicId: number) => {
  if (!confirm('确定要删除该主题吗？')) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/topics/${topicId}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      saveMessage.value = '主题删除成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      loadTopics()
    } else {
      const data = await response.json()
      saveMessage.value = '删除失败：' + (data.error || '未知错误')
      saveMessageType.value = 'error'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
    }
  } catch (err) {
    console.error('Delete topic error:', err)
    saveMessage.value = '删除失败：网络错误'
    saveMessageType.value = 'error'
    setTimeout(() => {
      saveMessage.value = ''
    }, 3000)
  }
}

// 关闭主题弹窗
const closeTopicModal = () => {
  showTopicModal.value = false
  // 重置表单
  newTopic.value = {
    title: '',
    description: '',
    color: '#42b983',
    icon: '📝'
  }
}
</script>

<style scoped>
.home {
  max-width: 800px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.header-buttons {
  display: flex;
  gap: 0.5rem;
}

h1 {
  color: #42b983;
  margin: 0;
}

.create-button {
  padding: 0.75rem 1.5rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.create-button:hover {
  background-color: #359c6d;
}

.folder-button {
  background-color: #ff9800;
}

.folder-button:hover {
  background-color: #f57c00;
}

.topic-button {
  background-color: #9c27b0;
}

.topic-button:hover {
  background-color: #7b1fa2;
}

/* 主题选择区域 */
.topics-section {
  margin-bottom: 2rem;
}

.topics-section h3 {
  margin-bottom: 1rem;
  color: #333;
}

.topics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.topic-card {
  display: flex;
  align-items: center;
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.topic-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.topic-card.active {
  border-color: currentColor;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
}

.topic-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: white;
  margin-right: 1rem;
}

.topic-info h4 {
  margin: 0 0 0.25rem 0;
  color: #333;
  font-size: 1rem;
}

.topic-info p {
  margin: 0;
  color: #666;
  font-size: 0.875rem;
}

.topic-hint {
  color: #999;
  font-size: 0.75rem;
  font-style: italic;
  margin-top: 0.25rem;
  display: block;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 1.5rem;
}

/* 创建主题表单 */
.create-topic-form {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e0e0e0;
}

.create-topic-form h4 {
  margin: 0 0 1rem 0;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-group input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.1);
}

/* 图标选择器 */
.icon-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.icon-option {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1.2rem;
  transition: all 0.3s;
}

.icon-option:hover {
  border-color: #42b983;
}

.icon-option.selected {
  border-color: #42b983;
  background-color: #42b983;
}

/* 颜色选择器 */
.color-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.color-option {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  border: 3px solid transparent;
  transition: all 0.3s;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.selected {
  border-color: #333;
  transform: scale(1.1);
}

/* 按钮样式 */
.btn-primary {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

.btn-primary:hover:not(:disabled) {
  background-color: #359c6d;
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  margin-right: 0.5rem;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
}

.btn-danger:hover {
  background-color: #c82333;
}

/* 现有主题列表 */
.existing-topics h4 {
  margin: 0 0 1rem 0;
  color: #333;
}

.topic-list {
  max-height: 300px;
  overflow-y: auto;
}

.topic-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 0.5rem;
}

.topic-preview {
  display: flex;
  align-items: center;
  flex: 1;
}

.topic-preview .topic-icon {
  width: 30px;
  height: 30px;
  font-size: 1rem;
  margin-right: 0.75rem;
}

.topic-details h5 {
  margin: 0 0 0.25rem 0;
  color: #333;
  font-size: 0.9rem;
}

.topic-details p {
  margin: 0;
  color: #666;
  font-size: 0.8rem;
}

.topic-actions {
  display: flex;
  align-items: center;
}

.default-badge {
  background-color: #28a745;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

/* 保存提示样式 */
.save-message {
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 15px;
  text-align: center;
  font-weight: bold;
}

.save-message.success {
  background-color: #4caf50;
  color: white;
}

.save-message.error {
  background-color: #f44336;
  color: white;
}

.documents-section h2 {
  margin-bottom: 1rem;
}

.loading, .empty-state {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.documents-tree {
  display: flex;
  flex-direction: column;
}
</style>
